package com.ktjy.ktmall.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjy.common.annotation.Log;
import com.ktjy.common.core.controller.BaseController;
import com.ktjy.common.core.domain.AjaxResult;
import com.ktjy.common.core.page.TableDataInfo;
import com.ktjy.common.enums.BusinessType;

import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ktjy.ktmall.domain.Banner;
import com.ktjy.ktmall.service.IBannerService;


/**
 * 轮播图管理Controller
 *
 * @author ktjy
 * @date 2025-03-15
 */
@RestController
@RequestMapping("/ktmall/banner")
public class BannerController extends BaseController
{
    @Autowired
    private IBannerService bannerService;

/**
 * 查询轮播图管理列表
 */
@PreAuthorize("@ss.hasPermi('ktmall:banner:list')")
@GetMapping("/list")
    public TableDataInfo list(Banner banner)
    {
        startPage();
        List<Banner> list = bannerService.selectBannerList(banner);
        return getDataTable(list);
    }


    /**
     * 导出轮播图管理列表
     */
    @PreAuthorize("@ss.hasPermi('ktmall:banner:export')")
    @Log(title = "轮播图管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Banner banner) throws IOException {
        QueryWrapper<Banner> queryWrapper = new QueryWrapper<>();
        if (banner.getType()!=null){
            queryWrapper.eq("type",banner.getType());
        }
        if (banner.getEnabled()!=null){
            queryWrapper.eq("enabled",banner.getEnabled());
        }
        List<Banner> list = bannerService.list(queryWrapper);

        // 添加序号列
        List<Map<String, Object>> exportList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Banner banner1 = list.get(i);
            Map<String, Object> exportData = new LinkedHashMap<>();
            exportData.put("index", i + 1); // 序号列的值自增，从1开始
            exportData.put("img_url", banner1.getImgUrl());
            exportData.put("href_url", banner1.getHrefUrl());
            exportData.put("remark", banner1.getRemark());
            exportData.put("type", banner1.getType() == 1 ? "首页":"分类商品页");
            exportData.put("enabled", banner1.getEnabled()==0 ? "正常":"禁用");

            // 把exportData这个键值对集合添加到上面定义的exportList集合中
            // 注意看上面定义时是（List<Map<String, Object>>）
            exportList.add(exportData);
        }
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.setOnlyAlias(true); // 设置成只导出有别名的字段
        // 自定义标题别名
        writer.addHeaderAlias("index", "编号");
        writer.addHeaderAlias("img_url", "轮播图");
        writer.addHeaderAlias("href_url", "跳转链接");
        writer.addHeaderAlias("type", "跳转类型");
        writer.addHeaderAlias("enabled", "状态");
        writer.addHeaderAlias("remark", "备注");
        // 合并单元格
        writer.merge(5, "轮播图信息");
        // 自定义样式（背景色为绿色，字体为黑色）
        CellStyle greenStyle = writer.getWorkbook().createCellStyle();
        greenStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        greenStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        greenStyle.setAlignment(HorizontalAlignment.CENTER); // 添加居中对齐
        Font font = writer.getWorkbook().createFont();
        font.setColor(IndexedColors.BLACK.getIndex());
        greenStyle.setFont(font);
        // 设置第一行的样式，包括合并的单元格
        writer.setStyle(greenStyle, 0, 0);
        // 一次性写出列表内的对象到Excel，使用默认样式，强制输出标题，并排除不需要导出的列
        writer.write(exportList, true);

        // 设置浏览器响应的格式
        String fileName = URLEncoder.encode("轮播图信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * 获取轮播图管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('ktmall:banner:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bannerService.getById(id));
    }

    /**
     * 新增轮播图管理
     */
    @PreAuthorize("@ss.hasPermi('ktmall:banner:add')")
    @Log(title = "轮播图管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Banner banner)
    {
        return toAjax(bannerService.save(banner));
    }

    /**
     * 修改轮播图管理
     */
    @PreAuthorize("@ss.hasPermi('ktmall:banner:edit')")
    @Log(title = "轮播图管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Banner banner)
    {
        return toAjax(bannerService.updateById(banner));
    }

    /**
     * 删除轮播图管理
     */
    @PreAuthorize("@ss.hasPermi('ktmall:banner:remove')")
    @Log(title = "轮播图管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Integer> ids)
    {
        return toAjax(bannerService.removeByIds(ids));
    }
}